/*
 * @Description: 实例管理
 * @Author: DHL
 * @Date: 2022-09-15 16:20:19
 * @LastEditors: DHL
 * @LastEditTime: 2023-11-16 18:26:20
 */

import { ElMessage, ElMessageBox } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '@/types/table.d'
import { arraySerializeToStr } from '@/utils/arrayUtils'
import usePermission from '@/hooks/web/permission'
import { ActHiProcinstModel, ActHiProcinstPageParams } from '@/api/flow/model/actHiProcinstModel'
import { apiActHiProcinstBatchDeleteByIds, apiActHiProcinstSearch } from '@/api/flow/actHiProcinst'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import flowCategoryTree from '../components/flowCategoryTree.vue'
import { apiFlowProcessDelete, apiFlowProcessStop } from '@/api/flow/flowProcess'
import twFlowchartPopup from '@/pages/flow/twFlow/twFlowchart/twFlowchartPopup.vue'
import twFlowLog from '@/pages/flow/twFlow/twFlowLog/index.vue'

export default defineComponent({
  name: 'ActHiProcinst',
  components: { Splitpanes, Pane, flowCategoryTree, twFlowchartPopup, twFlowLog },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    // 权限控制
    const { hasPermission } = usePermission()

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 公共
     */
    const state = reactive({})

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<ActHiProcinstModel> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      queryLikeStr: '', // 模糊查询关键字
      id: null, // 主键
      rev: null, //
      procInstId: null, // 流程实例ID
      businessKey: null, // 业务标识
      procDefId: null, // 流程定义ID
      startTime: null, // 开始时间
      endTime: null, // 结束时间
      duration: null, // 耗时
      startUserId: null, // 流程发起人ID
      startActId: null, // 开始节点ID
      endActId: null, // 结束节点ID
      superProcessInstanceId: null, // 父流程实例ID
      deleteReason: null, // 删除原因
      tenantId: null, // 租户ID
      name: null, // 名称
      callbackId: null, //
      callbackType: null, //
      referenceId: null, //
      referenceType: null, //
      propagatedStageInstId: null, //
      businessStatus: null // 业务状态
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: 'actHiProcinstTable',
      sortConfig: {
        defaultSort: [{ field: 'startTime', order: 'desc' }]
      },
      columns: [
        { type: 'checkbox', fixed: 'left', title: '', align: 'center', width: 40 },
        { type: 'seq', fixed: 'left', title: '序号', width: 50 },
        { field: 'name', title: '名称', sortable: true, minWidth: 200 },
        { field: 'procDefName', title: '流程定义', sortable: true, width: 120 },
        { field: 'procDefKey', title: '流程编码', sortable: true, width: 180 },
        { field: 'procDefCategoryName', title: '流程分类', sortable: true, width: 110 },
        { field: 'startTime', title: '开始时间', sortable: true, width: 150 },
        { field: 'endTime', title: '结束时间', sortable: true, width: 150 },
        { field: 'duration', title: '耗时', sortable: true, width: 100 },
        { field: 'startUserName', title: '发起人', sortable: true, width: 80 },
        { field: 'deleteReason', title: '删除原因', sortable: true, width: 110 },
        { field: 'businessStatus', title: '业务状态', sortable: true, width: 100 },
        { field: 'businessKey', title: '业务标识', sortable: true, width: 250 },
        { field: 'procInstId', title: '流程实例ID', sortable: true, width: 260 },
        { field: 'procDefId', title: '流程定义ID', sortable: true, width: 280 },

        { title: '操作', fixed: 'right', width: 230, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({
      cellDblclick(params: { row: ActHiProcinstModel }) {
        if (hasPermission('ACT-HI-PROCINST-VIEW')) {
        } else {
          ElMessage.warning('无权限访问')
        }
      }
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: ActHiProcinstPageParams) {
      loading.value = true
      apiActHiProcinstSearch(
        assign(queryParams, searchForm, {
          category: selectTreeNode.code
        })
      )
        .then((result) => {
          tableData.value = result
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 批量删除
     */
    function handleDelete(row: ActHiProcinstModel) {
      ElMessageBox.confirm(`此操作将删除1条记录, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loading.value = true

          apiFlowProcessDelete({ processInstanceId: row.procInstId, businessKey: row.businessKey })
            .then((result) => {
              if (result?.success) {
                handleRefresh()
                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
        })
        .catch(() => {
          ElMessage.info('删除被取消了')
        })
    }

    /**
     * 流程终止
     * @param row
     */
    function handleStop(row?: ActHiProcinstModel) {
      let selectRows: Array<ActHiProcinstModel> = []

      if (row) {
        selectRows = [row]
      } else {
        selectRows = tableRef.value.getSelectRows()
      }

      if (selectRows.length === 0) {
        ElMessage.warning('请选择需要终止的数据')
        return
      } else if (selectRows.length > 1) {
        ElMessage.warning('请选择一条需要终止的数据')
        return
      }

      ElMessageBox.confirm(`此操作将终止${selectRows.length}条记录, 是否继续?`, '终止提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loadingByDel.value = true

          const row = selectRows[0]

          apiFlowProcessStop({ businessKey: row.businessKey })
            .then((result) => {
              if (result?.success) {
                handleRefresh()
                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => {})
            .finally(() => {
              loadingByDel.value = false
            })
        })
        .catch(() => {
          ElMessage.info('终止被取消了')
        })
    }

    //////////////////////////////////////////////////
    // 流程类别树
    //////////////////////////////////////////////////
    const flowCategoryTreeRef = ref()

    /**
     * 选中的树节点
     */
    let selectTreeNode: any = {}

    /**
     * 节点点击事件
     */
    function handleNodeClick(treeNode?: Node) {
      selectTreeNode = treeNode ? treeNode : {}
      handleSearch()
    }

    /**
     * 树刷新
     */
    function handleTreeSearch() {}

    //////////////////////////////////////////////////
    // 流程图
    //////////////////////////////////////////////////
    const previewFlowchartRef = ref()

    /**
     * 弹出流程图预览
     */
    function handlePreviewFlowchart(row) {
      previewFlowchartRef.value.handleOpen({ procInstId: row.procInstId })
    }

    //////////////////////////////////////////////////
    // 审批日志
    //////////////////////////////////////////////////
    const twFlowLogRef = ref()

    /**
     * 弹出流程图预览
     */
    function handleFlowLog(row) {
      twFlowLogRef.value.handleOpen(row)
    }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => {})

    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      state,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      flowCategoryTreeRef,
      handleNodeClick,
      handleTreeSearch,
      previewFlowchartRef,
      handlePreviewFlowchart,
      handleStop,
      twFlowLogRef,
      handleFlowLog
    }
  }
})
